<?php
namespace app\api\controller;
use app\model\WxMsg as WxMsgModel;
use app\model\WxAssistant as WxAssistantModel;
use think\Db;

use app\lib\baidu\Api as baiduApi;
use app\lib\baidu\Api360 as api360;


class WxMsg extends Base
{

    public function getToken($message,$wx_assistant_id,$config_id=''){
        if (strpos($wx_assistant_id,'member_') !== false) {
            $member_id = str_replace('member_', '', $wx_assistant_id);
            $member = Db::name('wx_member')->where('id',$member_id)->find();
            $wx_assistant_id = $member['wx_assistant_id'];
        }
        $user_id = $this->login_user['user_id'];
        $message = trim($message);
        if (empty($message)) {
            return json(['code'=>5000]);
        }
        $check_msg = preg_replace("/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u", '', $message);
        $check_msg = strtolower($check_msg);
        if (empty($check_msg)) {
            return json(['code'=>5000]);
        }

        $assistant = Db::name('wx_assistant')->where('id',$wx_assistant_id)->find();
        if (!empty($config_id)) {
            $config = Db::name('wx_assistant_config')->where('id',$config_id)->find();
            $data['type'] = $config['type'];
            $data['request_type'] = $config['request_type'];
            $data['api_url'] = $config['api_url'];
            $data['api_param'] = $config['api_param'];
        }

        $api_url = $assistant['api_url'];
        $api_param = json_decode($assistant['api_param'],true);

        if ($assistant['type'] == 'baidu') {
            $api = new baiduApi();
            $token = $api->token($api_param);
            if (empty($token['access_token'])) {
                return json(['code'=>5000,'msg'=>'token获取失败']);
            }
            $messages = $this->getMessages($wx_assistant_id,$message,$member_id);
            return json(['code'=>2000,'data'=>[
                'api_url'=>$api_url,
                'access_token'=>$token['access_token'],
                'messages'=>$messages,
                'uuid'=>uuidCreate()
            ]]);
        }
    }
    
    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function index($wx_assistant_id,$user_id=''){
        if (strpos($wx_assistant_id,'member_') !== false) {
            $member_id = str_replace('member_', '', $wx_assistant_id);
            $member = Db::name('wx_member')->where('id',$member_id)->find();
            $wx_assistant_id = $member['wx_assistant_id'];
        }
        if (empty($user_id)) {
            $user_id = $this->login_user['user_id'];
        }
        $map_params = [
            
        ];
        $map = getSearchParam($map_params);
        $map[] = ['wx_assistant_id','=',$wx_assistant_id];
        $map[] = ['user_id','=',$user_id];
        if (input('id',0) > 0) {
            $map[] = ['id','>',input('id')];
        }
        if (!empty($member)) {
            $map[] = ['member_id','=',$member['id']];
        }else{
            $map[] = ['member_id','=',0];
        }

        $order_type = 'id desc';

        $uinfo = Db::name('user')->field('nickname,mobile,headimgurl')->where('id',$user_id)->find();

        $model = new WxMsgModel();
        $page_size = input('page_size',10);
        $page_param = ['page'=>input('page_index',1),'list_rows'=>$page_size];
        $list = $model->where($map)->order($order_type)->paginate($page_param)->toarray();
        $list['data'] = array_reverse($list['data']);
        if ($list['total'] < $page_size) {
            if (!empty($member)) {
                $frist_time = empty($list['data'][count($list['data'])-1]['ctime']) ? time() : $list['data'][count($list['data'])-1]['ctime'];
                array_unshift($list['data'],[
                    'id'=>0,
                    'user_id'=>$user_id,
                    'wx_assistant_id'=>$wx_assistant_id,
                    'message'=>'',
                    'ctime'=>$frist_time,
                    'duration'=>0,
                    'rtime'=>$frist_time,
                    'reply'=>'你好，我是'.$member['name'].'，'.$member['description']
                ]);
            }else{
                $assistant = Db::name('wx_assistant')->where('id',$wx_assistant_id)->find();
                if (!empty($assistant['greet'])) {
                    $frist_time = empty($list['data'][count($list['data'])-1]['ctime']) ? time() : $list['data'][count($list['data'])-1]['ctime'];
                    array_unshift($list['data'],[
                        'id'=>0,
                        'user_id'=>$user_id,
                        'wx_assistant_id'=>$wx_assistant_id,
                        'message'=>'',
                        'ctime'=>$frist_time,
                        'duration'=>0,
                        'rtime'=>$frist_time,
                        'reply'=>$assistant['greet']
                    ]);
                    // $list['data'][] = [
                    //     'id'=>0,
                    //     'user_id'=>$user_id,
                    //     'wx_assistant_id'=>$wx_assistant_id,
                    //     'message'=>'',
                    //     'ctime'=>$frist_time,
                    //     'duration'=>0,
                    //     'rtime'=>$frist_time,
                    //     'reply'=>$assistant['greet']
                    // ];
                }
            }
            
        }
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['user'] = $uinfo;
        }
        return apiResult('2000','获取成功',$list);
    }

    public function getMessages($wx_assistant_id,$message,$member_id=''){
        $user_id = $this->login_user['user_id'];
        $map = [
            ['wx_assistant_id','=',$wx_assistant_id],
            ['user_id','=',$user_id]
        ];
        if (!empty($member_id)) {
            $map[] = ['member_id','=',$member_id];
        }else{
            $map[] = ['member_id','=',0];
        }
        $msgs = Db::name('wx_msg')->field('message,reply')->where($map)->order('id','desc')->limit(3)->select();
        $messages = [];

        // for($i = count($msgs) - 1;$i >= 0;$i--){
        for($i = 0;$i < count($msgs);$i++){
            if (empty($msgs[$i]['message']) || empty($msgs[$i]['reply'])) {
                continue;
            }
            $messages[] = [
                'role'=>'user',
                'content'=>$msgs[$i]['message']
            ];
            $messages[] = [
                'role'=>'assistant',
                'content'=>$msgs[$i]['reply']
            ];
        }
        $messages[] = [
            'role'=>'user',
            'content'=>$message
        ];

        if (count($messages) > 1 && count($messages) % 2 == 0) {
            array_shift($messages);
        }

        return $messages;
    }

    public function save(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $ulogin = $this->login_user;
        $fields = [
            'must'=>['wx_assistant_id','message'],
            'nomust'=>['reply']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }

        $wx_assistant_id = $save_data['wx_assistant_id'];
        $member_id = 0;
        if (strpos($wx_assistant_id,'member_') !== false) {
            $member_id = str_replace('member_', '', $wx_assistant_id);
            $member = Db::name('wx_member')->where('id',$member_id)->find();
            $wx_assistant_id = $member['wx_assistant_id'];

            $save_data['wx_assistant_id'] = $wx_assistant_id;
            $save_data['member_id'] = $member['id'];
        }

        $assistant = Db::name('wx_assistant')->where('id',$wx_assistant_id)->find();
        $save_data['user_id'] = $ulogin['user_id'];
        $save_data['ctime'] = time();
        $save_data['rtime'] = time() + 1;
        $save_data['duration'] = 1;
        $save_data['config_type'] = $assistant['type'];
        $save_data['id'] = Db::name('wx_msg')->insertGetId($save_data);

        // 记录用户会话
        $uassistant_id = Db::name('wx_uassistant')->where([
            ['user_id','=',$save_data['user_id']],
            ['wx_assistant_id','=',$save_data['wx_assistant_id']],
            ['member_id','=',$member_id]
        ])->value('id');
        if ( empty($uassistant_id) ) {
            Db::name('wx_uassistant')->insert([
                'user_id'=>$save_data['user_id'],
                'wx_assistant_id'=>$save_data['wx_assistant_id'],
                'member_id'=>$member_id,
                'ctime'=>time(),
                'utime'=>time(),
                'content'=>$save_data['message']
            ]);
        }else{
            Db::name('wx_uassistant')->where('id',$uassistant_id)->update(['utime'=>time(),'content'=>$save_data['message']]);
        }
        
        return apiResult('2000','保存成功',$save_data);
    } 
 
    public function chatapi($message,$wx_assistant_id,$config_id=''){
        set_time_limit ( 0 );
        ini_set('memory_limit','-1');
        ini_set('max_execution_time',0);

        $member_id = 0;
        if (strpos($wx_assistant_id,'member_') !== false) {
            $member_id = str_replace('member_', '', $wx_assistant_id);
            $member = Db::name('wx_member')->where('id',$member_id)->find();
            $wx_assistant_id = $member['wx_assistant_id'];
        }

        $ulogin = $this->login_user;

        $curtime = time();
        $message = trim($message);
        if (empty($message)) {
            return apiResult('5000','消息不能为空');
        }
        // 去除特殊字符
        $check_msg = preg_replace("/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u", '', $message);
        $check_msg = strtolower($check_msg);
        if (empty($check_msg)) {
            return apiResult('5000','消息不能为空');
        }
        

        $assistant = Db::name('wx_assistant')->where('id',$wx_assistant_id)->find();
        if (!empty($config_id)) {
            $config = Db::name('wx_assistant_config')->where('id',$config_id)->find();
            $data['type'] = $config['type'];
            $data['request_type'] = $config['request_type'];
            $data['api_url'] = $config['api_url'];
            $data['api_param'] = $config['api_param'];
        }
        
        $api_url = $assistant['api_url'];
        $api_param = json_decode($assistant['api_param'],true);
        $save_data = [
            'user_id'=>$ulogin['user_id'],
            'wx_assistant_id'=>$wx_assistant_id,
            'message'=>$message,
            'ctime'=>$curtime,
        ];

        if (!empty($member)) {
            $assistant['system'] = '我是'.$member['name'].'，'.$member['description'];
            $save_data['member_id'] = $member['id'];
        }


        if ($assistant['type'] == 'justchat') {
            $api_url = 'http://brain.digitextend.com/api/ai/get_answer';
            $data = [
                'app_key'=>'1iizu98ocoy79fpa',
                'request_id'=>uuidCreate(),
                'timestamp'=>time(),
            ];
            $data['sign'] = http_build_query($data).'&79575b9988e514121233570d014c776512f4028a';
            $data['sign'] = strtoupper(md5($data['sign']));
            $data['param'] = [
                'session_id'=>$session_id,
                'prompt'=>$message,
                'voice'=>false
            ];

            $result = httpRequest($api_url,json_encode($data,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type:application/json',
            ]);
            $result = json_decode($result,true);
            
            if ($result['code'] == '0') {
                $is_success = 1;
                $is_shoufei = 1;
                $reply = $result['data']['answer'];
            }else{
                $is_success = 0;
                $reply = '这个问题太高深了，容我学习深造后再告诉你';
            }
        }elseif ($assistant['type'] == 'baidu') {
            $api = new baiduApi();
            $token = $api->token($api_param);
            if (empty($token['access_token'])) {
                return json(['code'=>5000,'msg'=>'token获取失败']);
            }
            $messages = $this->getMessages($wx_assistant_id,$message);
            $result = $api->chat($api_url,$token['access_token'],$messages,$assistant['system']);

            if ($result['status'] == 1) {
                $is_success = 1;
                $is_shoufei = 1;
                $reply = $result['answer'];
            }elseif ($result['status'] == 2) {
                $is_success = 1;
                $reply = $result['answer'];
            }else{
                $is_success = 0;
                $reply = '这个问题太高深了，容我学习深造后再告诉你';
            }
        }

        $save_data['reply'] = $reply;
        $save_data['rtime'] = time();
        $save_data['config_type'] = $assistant['type'];
        $save_data['duration'] = time() - $curtime;
        $save_data['id'] = Db::name('wx_msg')->insertGetId($save_data);

        // 记录用户会话
        $uassistant_id = Db::name('wx_uassistant')->where([
            ['user_id','=',$save_data['user_id']],
            ['wx_assistant_id','=',$save_data['wx_assistant_id']],
            ['member_id','=',$member_id]
        ])->value('id');
        if ( empty($uassistant_id) ) {
            Db::name('wx_uassistant')->insert([
                'user_id'=>$save_data['user_id'],
                'wx_assistant_id'=>$save_data['wx_assistant_id'],
                'member_id'=>$member_id,
                'ctime'=>time(),
                'utime'=>time(),
                'content'=>$save_data['message']
            ]);
        }else{
            Db::name('wx_uassistant')->where('id',$uassistant_id)->update(['utime'=>time(),'content'=>$save_data['message']]);
        }

        if ($is_success == 1) {
            return apiResult('2000','获取成功',$save_data);
        }else{
            return apiResult('2000','获取成功',$save_data);
        }
    }

    public function chatapiSwitch($msg_id,$config_type){
        set_time_limit ( 0 );
        ini_set('memory_limit','-1');
        ini_set('max_execution_time',0);
        
        $curtime = time();
        $data = Db::name('wx_msg')->where('id',$msg_id)->find();
        $assistant = Db::name('wx_assistant')->where('id',$data['wx_assistant_id'])->find();

        $config = WxAssistantModel::getConfigType($config_type);
        $api_url = $config['api_url'];
        $message = $data['message'];

        if ($config_type == 'ali') {
            $params = [
                'model'=>'qwen-turbo',
                'input'=>[
                    'prompt'=>$message,
                ]
            ];

            $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type:application/json',
                'Authorization:Bearer '.$config['api_id']
            ]);
            $result = json_decode($result,true);
            if (!empty($result['output']['text'])) {
                $is_success = 1;
                $reply = $result['output']['text'];
            }else{
                $is_success = 0;
                $reply = '这个问题太高深了，容我学习深造后再告诉你';
            }
        }elseif ($config_type == 'baidu') {
            $api = new baiduApi();
            $api_param = [
                'client_id'=>$config['api_id'],
                'client_secret'=>$config['api_secret'],
            ];
            $token = $api->token($api_param);
            if (empty($token['access_token'])) {
                return json(['code'=>5000,'msg'=>'token获取失败']);
            }
            // $messages = $this->getMessages($wx_assistant_id,$message);
            $messages[] = [
                'role'=>'user',
                'content'=>$message
            ];
            $result = $api->chat($api_url,$token['access_token'],$messages,$assistant['system']);

            if ($result['status'] == 1) {
                $is_success = 1;
                $reply = $result['answer'];
            }elseif ($result['status'] == 2) {
                $is_success = 1;
                $reply = $result['answer'];
            }else{
                $is_success = 0;
                $reply = '这个问题太高深了，容我学习深造后再告诉你';
            }
        }elseif ($config_type == '360') {
            $api = new api360();
            $api_param = [
                'yy_user_id'=>$config['yy_user_id'],
                'yy_user_name'=>$config['yy_user_name'],
                'model_id'=>$config['model_id'],
            ];
            $api_param['session_id'] = 'session_'.$data['wx_assistant_id'].'_'.$data['user_id'].'_'.$data['member_id'];
            $result = $api->chat($api_url,$message,$api_param);
            if ($result['status'] == 1) {
                $is_success = 1;
                $reply = $result['answer'];
            }elseif ($result['status'] == 2) {
                $is_success = 1;
                $reply = $result['answer'];
            }else{
                $is_success = 0;
                $reply = '这个问题太高深了，容我学习深造后再告诉你';
            }
        }

        $save_data = [];
        $save_data['reply'] = $reply;
        $save_data['rtime'] = time();
        $save_data['config_type'] = $config_type;
        $save_data['duration'] = time() - $curtime;

        // 更新内容
        Db::name('wx_msg')->where('id',$msg_id)->update($save_data);

        if ($is_success == 1) {
            return apiResult('2000','获取成功',$save_data);
        }else{
            return apiResult('2000','获取成功',$save_data);
        }
    }




   
}
